package com.blb.demo3;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP服务器端
 */
public class UDPServer {

    public static final int PORT = 8888;

    public void start(){
        System.out.println("启动UDP服务器");
        try {
            //创建服务器端对象
            DatagramSocket server = new DatagramSocket(PORT);
            while(true){
                //定义字节数组用于存放数据
                byte[] data = new byte[1024];
                DatagramPacket packet = new DatagramPacket(data,0,data.length);
                //接收数据包
                server.receive(packet);
                //将字节数据转换为字符串
                String msg = new String(packet.getData(),0,packet.getLength());
                System.out.println("服务器收到：" + msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UDPServer().start();
    }
}
